package com.jsh.erp.service.demo;

import com.alibaba.fastjson.JSONObject;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.datasource.entities.AccountHead;
import com.jsh.erp.datasource.entities.DepotHead;
import com.jsh.erp.datasource.entities.Demo;
import com.jsh.erp.datasource.entities.DemoExample;
import com.jsh.erp.datasource.mappers.AccountHeadMapperEx;
import com.jsh.erp.datasource.mappers.DepotHeadMapperEx;
import com.jsh.erp.datasource.mappers.DemoMapper;
import com.jsh.erp.datasource.mappers.DemoMapperEx;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.service.log.LogService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DemoService {
    private Logger logger = LoggerFactory.getLogger(DemoService.class);

    @Resource
    private DemoMapper demoMapper;

    @Resource
    private DemoMapperEx demoMapperEx;
    @Resource
    private UserService userService;
    @Resource
    private LogService logService;
    @Resource
    private AccountHeadMapperEx accountHeadMapperEx;
    @Resource
    private DepotHeadMapperEx depotHeadMapperEx;

    public Demo getDemo(long id)throws Exception {
        Demo result=null;
        try{
            result=demoMapper.selectByPrimaryKey(id);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    public List<Demo> getDemoListByIds(String ids)throws Exception {
        List<Long> idList = StringUtil.strToLongList(ids);
        List<Demo> list = new ArrayList<>();
        try{
            DemoExample example = new DemoExample();
            example.createCriteria().andIdIn(idList);
            list = demoMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<Demo> getDemo()throws Exception {
        DemoExample example = new DemoExample();
        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Demo> list=null;
        try{
            list=demoMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<Demo> select(String name, String type, int offset, int rows)throws Exception {
        List<Demo> list=null;
        try{
            list=demoMapperEx.selectByConditionDemo(name, type, offset, rows);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public Long countDemo(String name, String type)throws Exception {
        Long result=null;
        try{
            result=demoMapperEx.countsByDemo(name, type);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertDemo(JSONObject obj, HttpServletRequest request)throws Exception {
        Demo demo = JSONObject.parseObject(obj.toJSONString(), Demo.class);
        int result=0;
        try{
            result=demoMapper.insertSelective(demo);
            logService.insertLog("经手人",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(demo.getName()).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateDemo(JSONObject obj, HttpServletRequest request)throws Exception {
        Demo demo = JSONObject.parseObject(obj.toJSONString(), Demo.class);
        int result=0;
        try{
            result=demoMapper.updateByPrimaryKeySelective(demo);
            logService.insertLog("经手人",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(demo.getName()).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deleteDemo(Long id, HttpServletRequest request)throws Exception {
        return batchDeleteDemoByIds(id.toString());
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteDemo(String ids, HttpServletRequest request) throws Exception{
        return batchDeleteDemoByIds(ids);
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteDemoByIds(String ids)throws Exception {
        int result =0;
        String [] idArray=ids.split(",");
        //校验财务主表	jsh_accounthead
        List<AccountHead> accountHeadList =null;
        try{
            accountHeadList=accountHeadMapperEx.getAccountHeadListByHandsPersonIds(idArray);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        if(accountHeadList!=null&&accountHeadList.size()>0){
            logger.error("异常码[{}],异常提示[{}],参数,HandsDemoIds[{}]",
                    ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,ExceptionConstants.DELETE_FORCE_CONFIRM_MSG,ids);
            throw new BusinessRunTimeException(ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,
                    ExceptionConstants.DELETE_FORCE_CONFIRM_MSG);
        }
        //校验单据主表	jsh_depot_head
        List<DepotHead> depotHeadList =null;
        try{
            depotHeadList=depotHeadMapperEx.getDepotHeadListByCreator(idArray);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        if(depotHeadList!=null&&depotHeadList.size()>0){
            logger.error("异常码[{}],异常提示[{}],参数,HandsDemoIds[{}]",
                    ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,ExceptionConstants.DELETE_FORCE_CONFIRM_MSG,ids);
            throw new BusinessRunTimeException(ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,
                    ExceptionConstants.DELETE_FORCE_CONFIRM_MSG);
        }
        //记录日志
        StringBuffer sb = new StringBuffer();
        sb.append(BusinessConstants.LOG_OPERATION_TYPE_DELETE);
        List<Demo> list = getDemoListByIds(ids);
        for(Demo demo: list){
            sb.append("[").append(demo.getName()).append("]");
        }
        logService.insertLog("经手人", sb.toString(),
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        //删除经手人
        try{
            result=demoMapperEx.batchDeleteDemoByIds(idArray);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    public int checkIsNameExist(Long id, String name) throws Exception{
        DemoExample example = new DemoExample();
        example.createCriteria().andIdNotEqualTo(id).andNameEqualTo(name).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Demo> list =null;
        try{
            list=demoMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list==null?0:list.size();
    }

    public Map<Long,String> getDemoMap() throws Exception {
        List<Demo> demoList = getDemo();
        Map<Long,String> demoMap = new HashMap<>();
        for(Demo demo : demoList){
            demoMap.put(demo.getId(), demo.getName());
        }
        return demoMap;
    }

    public String getDemoByMapAndIds(Map<Long,String> demoMap, String demoIds)throws Exception {
        List<Long> ids = StringUtil.strToLongList(demoIds);
        StringBuffer sb = new StringBuffer();
        for(Long id: ids){
            sb.append(demoMap.get(id) + " ");
        }
        return sb.toString();
    }

    public List<Demo> getDemoByType(String type)throws Exception {
        DemoExample example = new DemoExample();
        example.createCriteria().andTypeEqualTo(type).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        example.setOrderByClause("id asc");
        List<Demo> list =null;
        try{
            list=demoMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }
}
